package com.louis.iread.ui;

import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.louis.iread.R;
import com.louis.iread.adapter.ClassPageAdapter;
import com.louis.iread.bean.ClassItem;
import com.louis.iread.bean.NovelPageItem;
import com.louis.iread.bean.Website;
import com.louis.iread.bean.WebsiteMgr;
import com.louis.iread.event.EventType;
import com.louis.iread.event.ReadEvent;
import com.louis.iread.net.HttpUtil;
import com.louis.iread.skin.SkinMgr;
import com.louis.iread.utils.ConstValue;
import com.louis.iread.utils.ThreadPool;
import com.yarolegovich.lovelydialog.LovelyProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class ClassActivity extends SwipeBackActivity {
    private int mPageNum = 1;
    private ClassItem mClassItem;
    private ListView mNovelListView;
    private ClassPageAdapter mAdapter;
    private Website mWebsite;
    private int mLastPageNum = 1;
    protected LovelyProgressDialog mDialog;
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SkinMgr.getInstance().register(this);
        setContentView(R.layout.activity_class);

        //实现沉浸式状态栏
        if (Build.VERSION.SDK_INT >= 19) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        //设置右划关闭页面
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_ALL);
        mClassItem = (ClassItem)getIntent().getSerializableExtra(ConstValue.CLASS_TYPE);
        mNovelListView = (ListView) findViewById(R.id.novel_list);
        TextView titleView = (TextView) findViewById(R.id.class_type);
        titleView.setText(mClassItem.getTitle());
        ImageView backView= (ImageView) findViewById(R.id.back);
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mAdapter = new ClassPageAdapter(this, R.layout.novel_page_item, com.louis.iread.BR.pageItem, new ArrayList<NovelPageItem>());
        mNovelListView.setAdapter(mAdapter);
        mNovelListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (view.getLastVisiblePosition() == view.getCount() - 1) {
                    mDialog = new LovelyProgressDialog(ClassActivity.this);
                    mDialog.setIcon(R.drawable.ic_cast_connected_white_36dp)
                            .setTitle(R.string.obtain_data)
                            .setCancelable(true);
                    mDialog.show();
                    showPage(mPageNum++);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        mWebsite = WebsiteMgr.getManager().getMainSite();
        EventBus.getDefault().register(this);
        mDialog = new LovelyProgressDialog(ClassActivity.this);
        mDialog.setIcon(R.drawable.ic_cast_connected_white_36dp)
                .setTitle(R.string.obtain_data)
                .setCancelable(true);
        mDialog.show();
        showPage(mPageNum++);
    }

    public void showPage(final int pageNum) {
        ThreadPool.getInstance().commit(new Runnable() {
            @Override
            public void run() {
                String url = mClassItem.getUrl().replace("{page}", new Integer(pageNum).toString());
                try {
                    String html = HttpUtil.getStringFromUrl(url, mWebsite.getUserAgent(), mWebsite.getHost(),null);
                    if (html == null || html.length() == 0) {
                        return;
                    }
                    Document document = Jsoup.parse(html);
                    if (document == null) {
                        EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                        return;
                    }
                    if (mLastPageNum == 1) {
                        String lastPageNum = document.select(mWebsite.getClassify().getLastPage()).first().text();
                        mLastPageNum = Integer.parseInt(lastPageNum);
                    }
                    List<NovelPageItem> list = new ArrayList<>();
                    Elements elements = document.select(mWebsite.getClassify().getNovelList());
                    for (Element element:elements) {
                        NovelPageItem item = new NovelPageItem();
                        String novelName = element.select(mWebsite.getClassify().getNovelName()).first().text().trim();
                        String novelCover = element.select(mWebsite.getClassify().getCover()).first().attr("src");
                        String novelAuthor = element.select(mWebsite.getClassify().getAuthor()).first().text().trim();
                        String novelUrl = element.select(mWebsite.getClassify().getNovelUrl()).attr("href");
                        String latestArticle = element.select(mWebsite.getClassify().getLatestArticle()).first().text().trim();
                        String updateTime = element.select(mWebsite.getClassify().getUpdateTime()).first().text();
                        item.setNovelName(novelName.replace("TXT", "").replace("下载", "").trim());
                        if (!updateTime.startsWith("20")) {
                            item.setUpdateTime("20" + updateTime);
                        } else {
                            item.setUpdateTime(updateTime);
                        }
                        item.setCover(novelCover);
                        item.setAuthor(novelAuthor);
                        item.setLatestArticle(latestArticle);

                        Pattern pattern = Pattern.compile(mWebsite.getClassify().getNovelId());
                        Matcher matcher = pattern.matcher(novelUrl);
                        if (!matcher.find()) {
                            break;
                        }
                        item.setNovelId(matcher.group(1));
                        item.setNovelUrl(mWebsite.getMainUrl().replace("{novelId}", item.getNovelId()));
                        item.setContentsUrl(mWebsite.getContentsUrl().replace("{novelId}", item.getNovelId()));
                        item.setType(mClassItem.getTitle());
                        list.add(item);
                    }
                    EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_SUCCESS, list));
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    EventBus.getDefault().post(new ReadEvent(EventType.LOAD_PAGE_FAILED));
                }

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(ReadEvent event) {
        if (event.getEventType() == EventType.LOAD_PAGE_SUCCESS) {
            mAdapter.addItems((List<NovelPageItem>) event.getObj());
            mAdapter.notifyDataSetChanged();
        } else if (event.getEventType() == EventType.LOAD_PAGE_FAILED) {
            Toast.makeText(this, R.string.download_failed, Toast.LENGTH_LONG).show();
        }
        mDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SkinMgr.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
    }
}
